package com.jt.service.impl;

import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import com.jt.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

@Service
public class MenuServiceImpl implements MenuService {
    private static final Logger log=
            LoggerFactory.getLogger(MenuServiceImpl.class);
    @Autowired
    private MenuMapper menuMapper;
//    @Autowired
//    private RedisTemplate redisTemplate;

    //参考官方的一种写法
    @Resource(name="redisTemplate")
    private ValueOperations valueOperations;


    //存储到redis中
    @Override
    public Menu selectById(Long id) {
        //1.从redis缓存查询数据，假如有则直接返回缓存中数据
//        ValueOperations vo = redisTemplate.opsForValue();
//        String key =String.valueOf(id);
//        Object obj = vo.get(key);
        Object obj=valueOperations.get(String.valueOf(id));
        if (obj!=null){
            log.info("data from redis");
            return (Menu)obj;
        }
        //2.redis缓存没有则查询关系数据库
        Menu menu = menuMapper.selectById(id);
        log.info("data from redis");
//        vo.set(key,menu, Duration.ofSeconds(180));
        //3.将数据存储到redis缓存
        valueOperations.set(String.valueOf(id), menu, Duration.ofSeconds(120));

        return menu;
    }
    @Override
    public Menu insertMenu(Menu menu) {
        log.info("insert.before:{}",menu);
        menuMapper.insert(menu);
        log.info("insert.after:{}",menu);
        //写入redis
//        ValueOperations vo = redisTemplate.opsForValue();
//        vo.set(String.valueOf(menu.getId()),menu);
        valueOperations.set(String.valueOf(menu.getId()), menu, Duration.ofSeconds(120));
        return menu;//这里返回的menu会相对于参数多个id值
    }
    @Override
    public Menu updateMenu(Menu menu) {
        //更新mysql
        menuMapper.updateById(menu);
        //更新redis
        valueOperations.set(String.valueOf(menu.getId()),menu);
        return menu;
    }
}
